package com.hula.onion.book.server.spider.platforms.elutongxin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.SpiderCommon;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.utils.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by work on 2018/1/22.
 */
@Component("eLuTongXinSpider")
public class ELuTongXinSpider extends SpiderCommon {

    @Autowired
    private ELuTongXinSpiderHelper spiderHelper;

    private static final String CHECK_LOGIN = "https://m.88bank.com/secure/loginAjaxVerify";

    private static final String LOGIN_URL = "https://m.88bank.com/secure/dologin";

    private static final String ACCOUNT_INFO_URL = "https://m.88bank.com/account/overview";

    @Override
    public CommonResponse execute() {
        String checkResult = HttpUtils.post(CHECK_LOGIN,
                spiderHelper.installCheckParams(loginForm),
                getHttpContext());
        if (StringUtils.isEmpty(checkResult)) {
            return new CommonResponse(ResponseStatusEnum.FAIL);
        }
        JSONObject checkJson = JSON.parseObject(checkResult);
        if (!checkJson.getBoolean("successed")) {
            return new CommonResponse(ResponseStatusEnum.ACCOUNT_ERROR);
        }
        String loginStr = HttpUtils.post(LOGIN_URL,
                spiderHelper.installRequestParams(loginForm),
                getHttpContext());
        if (StringUtils.isEmpty(loginStr)) {
            return new CommonResponse(ResponseStatusEnum.FAIL);
        }
        if (spiderHelper.loginSuccess(loginStr)) {
            String accountHtml = HttpUtils.get(ACCOUNT_INFO_URL, getHttpContext());
            return spiderHelper.parseAccountBalance(accountHtml);
        } else {
            return new CommonResponse(ResponseStatusEnum.ACCOUNT_ERROR);
        }
    }
}
